﻿using IdentityModel;
using IdentityServer4.Extensions;
using IdentityServer4.Models;
using IdentityServer4.Services;
using Microsoft.AspNetCore.Identity;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace ZhengMeiJiSettingUI.Commom
{
    public class ProfileService : IProfileService
    {
        private readonly UserManager<IdentityUser> _userManager;

        public ProfileService(UserManager<IdentityUser> userManager)
        {
            _userManager = userManager;
        }

        public async Task GetProfileDataAsync(ProfileDataRequestContext context)
        {
            var sub = context.Subject.GetSubjectId();

            var user = await _userManager.FindByIdAsync(sub);

            if (user != null && user.ConcurrencyStamp != context.Subject.Claims.FirstOrDefault(x => x.Type == "AspNet.Identity.SecurityStamp")?.Value)
            {
               
                return;
            }

            var claims = new List<Claim>
        {
            new Claim(JwtClaimTypes.Subject, user.Id),
            new Claim(JwtClaimTypes.Name, user.UserName),
            new Claim(JwtClaimTypes.Email, user.Email)
        };

            context.IssuedClaims = claims;
        }

        public async Task IsActiveAsync(IsActiveContext context)
        {
            var sub = context.Subject.GetSubjectId();

            var user = await _userManager.FindByIdAsync(sub);

            if (user != null && user.ConcurrencyStamp != context.Subject.Claims.FirstOrDefault(x => x.Type == "AspNet.Identity.SecurityStamp")?.Value)
            {
                context.IsActive = false;
                return;
            }

            context.IsActive = user != null;
        }
    }

}
